package com.hzx.zhihu.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hzx.zhihu.annotation.Log;
import com.hzx.zhihu.domain.po.Result;

import com.hzx.zhihu.domain.po.User;
import com.hzx.zhihu.service.UserService;
import com.hzx.zhihu.utils.AliOssUtil;
import com.hzx.zhihu.utils.JwtUtil;
import com.hzx.zhihu.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //登录
    @PostMapping("/login")
    @Log(name = "用户登录")
    public Result login(@RequestBody Map<String, String> code) {
        // 从请求中获取用户名和密码
        String username = code.get("username");
        String password = code.get("password");

        // 校验用户名和密码
        if (username == null || password == null || username.trim().isEmpty() || password.trim().isEmpty()) {
            return Result.failure(400, "用户名或密码不能为空");
        }

        // 调用服务层登录方法
        Result<User> result = userService.login(username, password);
        if (result.getCode() != 200) {
            // 如果登录失败，返回失败信息
            return Result.failure(result.getCode(), result.getMessage());
        }

        // 登录成功，生成 token
        User user = result.getData();
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        String token = JwtUtil.genToken(claims);

        // 把 token 存储到 Redis 中，设置过期时间为 1 小时
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token, token, 1, TimeUnit.HOURS);


        Map map = new HashMap();
        map.put("token", token);
        map.put("user", user);
        // 返回成功结果
        return Result.success(map);
    }

    @PostMapping("/update")
    @Log(name = "用户更新")
    @Transactional // 增加事务管理
    public Result update(@RequestBody User user) {
        // 校验参数
        if (user.getId() == null) {
            return Result.failure(4003, "用户ID不能为空");
        }

        String email = user.getEmail();
        // 校验是否是邮箱
        if (email != null && !email.isEmpty()) {
            if (!email.contains("@")) {
                return Result.failure(4001, "邮箱格式错误");
            }
        }

        String phone = user.getPhone();
        // 校验是否为手机号
        if (phone != null && !phone.isEmpty()) {
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                return Result.failure(4002, "手机号格式错误");
            }
        }

        // 其他字段校验
        if (user.getUserName() == null || user.getUserName().isEmpty()) {
            return Result.failure(4004, "用户名不能为空");
        }

        try {
            System.out.println(user);
            user.setGmtModified(LocalDateTime.now());
            boolean update = userService.updateById(user);
            System.out.println(update);
            if (!update) {
                return Result.failure(400, "更新失败");
            } else {
                return Result.success("更新成功");
            }
        } catch (Exception e) {

            return Result.failure(500, "服务器内部错误");
        }
    }


    @PostMapping("/updateAvatar")
    @Log(name = "用户更新头像")
    public String updateAvatar(@RequestParam("avatar") MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(filename);
//        String url = AliOssUtil.uploadFile(filename, file.getInputStream());
        return "http://.....";
    }




    @GetMapping("/token")
    public Result token(){
        return null;
    }

}
